import datetime
import os
import requests

from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from database.database import get_db
from enums import Identity
from models.user import User
from schemas.user import WeChatLoginRequest

load_dotenv()

router = APIRouter()

@router.post("/login/", tags=["user"])
async def login(code: WeChatLoginRequest, db: Session=Depends(get_db)):
    app_id = os.getenv("APP_ID")
    app_secret = os.getenv("APP_SECRET")
    url = f"https://api.weixin.qq.com/sns/jscode2session?appid={app_id}&secret={app_secret}&js_code={code.code}&grant_type=authorization_code`"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        open_id = data["openid"]
        user = db.query(User).filter(User.open_id==open_id).first()
        if not user:
            new_user = User(
                open_id=open_id,
                identity=Identity.visitor.value,
                create_time=datetime.datetime.now(),
                update_time=datetime.datetime.now(),
            )
            db.add(new_user)
            db.commit()
            db.refresh(new_user)
        return {
            "success": True,
            "openid": open_id,
            "session_key": data["session_key"],
            # "unionid": data["unionid"]
        }
    else:
        return {
            "success": False,
            "err_msg": response.text
        }